import { Request, errorToast, thumbFileUrl, fileUrl } from '../../utils/util.js' 
let request = new Request()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    width : {
      type : String,
      value : "218rpx"
    },
    height : {
      type : String,
      value : '218rpx',
    },
    camera : {
      type : Boolean,
      value : true
    },
    initFile : {
      type : String,
      value : ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    rate : 0,
    uploadIng : false,
    url : '',
    thumb : ''
  },

  lifetimes : {
    ready () {
      let initFile = this.properties.initFile
      if (initFile !== ''){
        this.setData({ thumb: thumbFileUrl(initFile), url: initFile })
      }
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    clear () {
      this.setData({ url : '', thumb : ''})
      this.triggerEvent('clear')
    },
    selectUpload () {
      if(this.data.url !== ''){
        wx.previewImage({
          urls: [fileUrl(this.data.url)]
        })
        return
      }

      wx.chooseImage({
        sourceType: ['album', 'camera'],
        count : 1,
        success : (res) => {

          this.setData({ uploadIng : true})

          const tempFilePaths = res.tempFilePaths
          let task = request.upload('upload/uploadpic', tempFilePaths[0], res => {
            res = JSON.parse(res)
            if(res.success){
              let file = res.data.fileName
              this.setData({ thumb: thumbFileUrl(file), url : file})

              this.triggerEvent('success', { value: file, file: file})

            }else{
              errorToast('上传失败')
            }
          }, res => {
            errorToast('上传失败')
            this.setData({ uploadIng: false })
          })

          task.onProgressUpdate(res => {
            this.setData({ rate: res.progress})
          })

          task.onHeadersReceived(res => {
            this.setData({ uploadIng: false })
          })
        }
      })
    }
  }
})
